const axios = require('axios')
const process = require('process')
const fs = require('fs')

if (process.argv.length != 6) {
    console.log(`Usage: ksapps <ks> <workspae> <project> <username:password>`)
    process.exit(1)
}

const ks = process.argv[2]
const workspace = process.argv[3]
const project = process.argv[4]
const credential = process.argv[5]

const applications = 'applications=status%3Dcreating%7Cactive%7Cfailed%7Cdeleting%7Cupgrading%7Ccreated%7Cupgraded&paging=limit%3D1000%2Cpage%3D1&orderBy=status_time'
const url = `${ks}/kapis/openpitrix.io/v1/workspaces/${workspace}/namespaces/${project}/applications?${applications}`
const authorization = Buffer.from(credential).toString("base64")
axios(url, {
    method: 'GET',
    headers: {
        authorization: `Basic ${authorization}`
    }
}).then(v => {
    const dir = "helm-applications"
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir)
    }
    v.data.items.forEach(app => {
        const yaml = `${dir}/helm-${app.name}.yml`
        console.log(`Writing helm configuration into ${yaml} ... `)
        fs.writeFileSync(yaml, app.cluster.env)
    })
}).catch(a => {
    console.log(`Unexpected error occurs: ${a}`)
})
